package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.*;
import com.java1234.service.QuestionBankService;
import com.java1234.service.QuestionService;
import com.java1234.util.RedisUtil;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 题库Controller
 */
@RestController
@RequestMapping("/bsns/subject/questionBanks")
public class QuestionBankController {
    private static final Logger logger = LoggerFactory.getLogger(QuestionBankController.class);

    @Autowired private QuestionBankService questionBankService;

    @Autowired private QuestionService questionService;

    /**
     * 查询所有题库信息
     * @return
     */
    @GetMapping("/banklistAll")
    public R banklistAll(){
        Map<String,Object> resultMap=new HashMap<>();
        List<QuestionBank> banks = questionBankService.list();
        resultMap.put("banks",banks);
        return R.ok(resultMap);
    }

    /**
     * 分页查询题库信息
     * @param pageBean
     * @return
     */
    @PostMapping("/banklist")
    public R banklist(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<QuestionBank> pageRes=questionBankService.page(new Page<>(pageBean.getPageNum(),pageBean.getPageSize()),
            new QueryWrapper<QuestionBank>().like(StringUtil.isNotEmpty(query),"name",query));
        List<QuestionBank> banks = pageRes.getRecords();
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("banks",banks);
        resultMap.put("total",pageRes.getTotal());
        return R.ok(resultMap);
    }

    /**
     * 根据ID查询题库信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getBankById(@PathVariable(value="id") Long id) {
        QuestionBank questionBank = questionBankService.getById(id);
        if (questionBank == null) {
            return R.error("没找到");
        }
        return R.ok().put("banks", questionBank);
    }

    /**
     * 删除题库信息
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        for (Long id:ids){
            questionService.remove(new QueryWrapper<Question>().eq("bankid",id));
        }
        questionBankService.removeByIds(Arrays.asList(ids));
        return R.ok("删除成功");
    }

    /**
     * 保存题库信息
     * @param questionBank
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody QuestionBank questionBank){
        if(questionBank.getId()==null || questionBank.getId()==-1){
            questionBank.setCreatetime(new Date());
            questionBankService.save(questionBank);
            return R.ok("保存成功");
        }else{
            questionBank.setCreatetime(new Date());
            questionBankService.updateById(questionBank);
            return R.ok("修改成功");
        }
    }

    /**
     * 查询题库下的问题类型数量
     * @param id
     * @return
     */
    @GetMapping("/{id}/questionTypeCounts")
    public R getQuestionTypeCounts(@PathVariable(value = "id") Long id) {
        logger.info("拿到了问题类型的数量id: {}", id);
        Map<String, Object> resultMap = new HashMap<>();

        int singleChoiceCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 1));
        int multipleChoiceCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 2));
        int trueFalseCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 3));
        int fillInTheBankCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 4));

        resultMap.put("singleChoiceCount", singleChoiceCount);
        resultMap.put("multipleChoiceCount", multipleChoiceCount);
        resultMap.put("trueFalseCount", trueFalseCount);
        resultMap.put("fillInTheBankCount", fillInTheBankCount);

        return R.ok(resultMap);
    }
}
//@GetMapping("/banklistAll")
//public R banklistAll(){
//    String cacheKey = "banklistAll";
//    Map<String,Object> resultMap = (Map<String, Object>) redisUtil.get(cacheKey);
//
//    if (resultMap == null) {
//        resultMap = new HashMap<>();
//        List<QuestionBank> banks = questionBankService.list();
//        resultMap.put("banks", banks);
//        redisUtil.set(cacheKey, resultMap, 3600); // 缓存1小时
//    }
//
//    return R.ok(resultMap);
//}

//    @PostMapping("/banklist")
//    public R banklist(@RequestBody PageBean pageBean){
//        String query = pageBean.getQuery().trim();
//        String cacheKey = "banklist:" + query + ":" + pageBean.getPageNum() + ":" + pageBean.getPageSize();
//        Map<String,Object> resultMap = (Map<String, Object>) redisUtil.get(cacheKey);
//
//        if (resultMap == null) {
//            Page<QuestionBank> pageRes = questionBankService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
//                    new QueryWrapper<QuestionBank>().like(StringUtil.isNotEmpty(query), "name", query));
//            List<QuestionBank> banks = pageRes.getRecords();
//            resultMap = new HashMap<>();
//            resultMap.put("banks", banks);
//            resultMap.put("total", pageRes.getTotal());
//            redisUtil.set(cacheKey, resultMap, 3600); // 缓存1小时
//        }
//
//        return R.ok(resultMap);
//    }

//@GetMapping("/{id}")
//public R getBankById(@PathVariable(value="id") Long id) {
//    String cacheKey = "getBankById:" + id;
//    QuestionBank questionBank = (QuestionBank) redisUtil.get(cacheKey);
//
//    if (questionBank == null) {
//        questionBank = questionBankService.getById(id);
//        if (questionBank == null) {
//            return R.error("没找到");
//        }
//        redisUtil.set(cacheKey, questionBank, 3600); // 缓存1小时
//    }
//
//    return R.ok().put("banks", questionBank);
//}

//@Transactional
//@PostMapping("/delete")
//public R delete(@RequestBody Long[] ids){
//    for (Long id : ids) {
//        questionService.remove(new QueryWrapper<Question>().eq("bankid", id));
//        redisUtil.del("getBankById:" + id);
//        redisUtil.del("questionTypeCounts:" + id);
//    }
//    questionBankService.removeByIds(Arrays.asList(ids));
//    redisUtil.del("banklistAll");
//    return R.ok("删除成功");
//}

//@PostMapping("/save")
//public R save(@RequestBody QuestionBank questionBank){
//    if (questionBank.getId() == null || questionBank.getId() == -1) {
//        questionBank.setCreatetime(new Date());
//        questionBankService.save(questionBank);
//        redisUtil.del("banklistAll");
//    } else {
//        questionBank.setCreatetime(new Date());
//        questionBankService.updateById(questionBank);
//        redisUtil.del("getBankById:" + questionBank.getId());
//        redisUtil.del("questionTypeCounts:" + questionBank.getId());
//    }
//    return R.ok(questionBank.getId() == null ? "保存成功" : "修改成功");
//}


//    @GetMapping("/{id}/questionTypeCounts")
//    public R getQuestionTypeCounts(@PathVariable(value = "id") Long id) {
//        logger.info("拿到了问题类型的数量id: {}", id);
//        String cacheKey = "questionTypeCounts:" + id;
//        Map<String, Object> resultMap = (Map<String, Object>) redisUtil.get(cacheKey);
//
//        if (resultMap == null) {
//            resultMap = new HashMap<>();
//            int singleChoiceCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 1));
//            int multipleChoiceCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 2));
//            int trueFalseCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 3));
//            int fillInTheBankCount = questionService.count(new QueryWrapper<Question>().eq("bankid", id).eq("type", 4));
//
//            resultMap.put("singleChoiceCount", singleChoiceCount);
//            resultMap.put("multipleChoiceCount", multipleChoiceCount);
//            resultMap.put("trueFalseCount", trueFalseCount);
//            resultMap.put("fillInTheBankCount", fillInTheBankCount);
//
//            redisUtil.set(cacheKey, resultMap, 3600); // 缓存1小时
//        }
//
//        return R.ok(resultMap);
//    }